#include <stdio.h>
#include "WebServer.h"

int main(int argc, char const *argv[])
{
    // 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        perror("socket failed");
        return 0;
    }
    printf("已创建套接字\n");

    // 从文件中获取ip和端口
    FILE *fp = fopen("../node.json", "r");
    // 从文件中读取内容
    char buf[SIZE] = {0};
    fread(buf, 1, SIZE, fp);
    // 解析ip和端口
    char addr[32] = {0};
    int port = 0;
    printf("正在解析文件内容\n");
    cJSON *json = cJSON_Parse(buf);
    if(json == NULL)
    {
        printf("解析文件内容失败\n");
        return -1;
    }
    json = cJSON_GetObjectItem(json, "addr");
    json = cJSON_GetArrayItem(json, 1);
    if(strcmp(cJSON_GetObjectItem(json, "name")->valuestring, "webserver") == 0)
    {
        cJSON *addr_json = cJSON_GetObjectItem(json, "addr");
        cJSON *port_json = cJSON_GetObjectItem(json, "port");
        if(addr_json == NULL || port_json == NULL)
        {
            printf("获取ip和端口号失败，检查配置文件后重启服务器\n");
            return -1;
        }
        strcpy(addr, addr_json->valuestring);
        port = port_json->valueint;
    }

    // 设置地址重用
    int opt = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    // 设置网络信息
    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(addr);

    // 绑定网络信息
    if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
    {
        perror("bind failed");
        exit(3);
    }

    // 监听网络
    if (listen(sock, 5) < 0)
    {
        perror("listen failed");
        exit(4);
    }

    while (1)
    {
        printf("等待客户端连接\n");
        // 接收客户端连接
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int client_sock = accept(sock, (struct sockaddr *)&client, &len);
        if (client_sock < 0)
        {
            perror("accept failed");
            continue;
        }

        // 处理客户端请求
        handle_requests(client_sock);
    }
    return 0;
}
